//
//  XSJStatusListViewModel.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/14.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

class XSJStatusListViewModel: NSObject {
    var statusList : [XSJStatusViewModel]?
    
    func requestStatus(ispullUP: Bool, complete: (isSuccess: Bool, message: String)->()) {
        var maxId : Int64 = 0
        
        var sinceId : Int64 = 0
        
        if ispullUP {
        
            maxId = statusList?.last?.status?.id ?? 0
            if maxId > 0 {
            maxId -= 1
       
            }
            
        }
        else{
            
            sinceId = statusList?.first?.status?.id ?? 0
            

        }
        //        XSJNetWorkTools.sharedTools.requestStatus(XSJUserAccountViewModel.sharedUserAccount.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
        //            var message: String = "没有加载到微博数据"
        //            if error != nil {
        XSJStatusDAL.loadData(maxId, sinceId: sinceId) { (statusesArray) -> () in

            var message = "没有加载到微博数据"
            if statusesArray.count == 0 {

            print("网络请求异常")
                complete(isSuccess: false, message: message)
                return
            }

//            guard let dic = response as? [String : AnyObject] else{
//        
//            print("不是一个正确的json格式")
//            complete(isSuccess: false, message: message)
//            return
//            
//        }
////            print(dic)
//         guard let statusesArray = dic["statuses"] as? [[String: AnyObject]] else {
//            print("不是一个正确的json格式")
//            complete(isSuccess: false, message: message)
//            return
//        }
//        
//            XSJStatusDAL.cacheData(statusesArray)

            var tempArray = [XSJStatusViewModel]()
            for value in statusesArray {
                let status = XSJStatus(dic: value)
                let statusViewModel = XSJStatusViewModel(status: status)
                tempArray.append(statusViewModel)
            }
            if self.statusList == nil {
                self.statusList = [XSJStatusViewModel]()
            }

            

            
            if ispullUP {
            
                self.statusList! += tempArray
           

                
            }else{
            
                self.statusList = tempArray + self.statusList!
                
            }
            
                
                
            let count = tempArray.count
            if count > 0 {
            
                message = "加载了\(count)条微博数据"
           
            }
            
            complete(isSuccess: true, message: message)

        
        }
        
        
    }
}
